<template>
    <div class="app-container" v-loading="loading">
        <div class="action-container">
          <el-button  icon="el-icon-back" size="small" @click="$router.back(-1)" >返回</el-button>
          <el-button  icon="el-icon-plus" size="small" type="primary" @click='openAddDialog'>添加内容</el-button>
          <el-button  icon="el-icon-delete" size="small" @click="deleteContentes">批量删除</el-button>
          <el-button  icon="el-icon-refresh" size="small" @click='refresh'>刷新</el-button>
        </div>
        <el-table
                :data="tableData"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
            <el-table-column
                    prop="name"
                    label="名称" >
            </el-table-column>
          <el-table-column
            prop="title"
            label="标题" >
          </el-table-column>
          <el-table-column
            prop="introduce"
            label="简介" >
          </el-table-column>
          <el-table-column
            label="Logo"
            width="150">
            <template slot-scope="scope">
              <img :src="scope.row.photo" />
            </template>
          </el-table-column>
            <el-table-column
                    label="编辑"
                    align="left" min-width="160">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click='openEditDialog(scope.row)'></el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
                :total-elements="totalElements"
                :change-callback="getContentList"
                ref="page"></pagination>
        <el-dialog
                title="添加内容"
                :visible.sync="addArticleDialog"
                :before-close="closeAddDialog">
            <el-form :model="form">
                 <el-form-item label="语言类别" :label-width="formLabelWidth">
                    <el-select v-model="form.languageId" placeholder="请选择">
                      <el-option
                        v-for="item in langOptions"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value">
                      </el-option>
                    </el-select>
                </el-form-item>
                 <el-form-item label="内容名称" :label-width="formLabelWidth">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
              <el-form-item label="内容标题" :label-width="formLabelWidth">
                <el-input v-model="form.title"></el-input>
              </el-form-item>
              <el-form-item label="内容简介" :label-width="formLabelWidth">
                <el-input v-model="form.introduce"></el-input>
              </el-form-item>
              <el-form-item label="Logo" :label-width="formLabelWidth">
                <el-upload
                  class="logo-uploader"
                  :action="url"
                  :data="filesData"
                  name="files"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :on-error = "handleLogoFailed"
                  :before-upload="beforeLogoUpload"
                  :headers="headers">
                  <img v-if="imgSrc" :src="imgSrc" class="logo">
                  <i v-else class="el-icon-plus logo-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="外链" :label-width="formLabelWidth">
                <el-input v-model="form.outChain"></el-input>
              </el-form-item>
                <el-form-item label="内容内容" :label-width="formLabelWidth">
                   <rich-text-editor ref='editor2' :Id='1' :module="module"></rich-text-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click='closeAddDialog'>取 消</el-button>
                <el-button type="primary" @click="addContent" :loading="btnLoading">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog
                title="编辑内容"
                :visible.sync="editDialog"
                :before-close="closeEditDialog">
            <el-form :model="current">
                <el-form-item label="语言类别" :label-width="formLabelWidth">
                    <el-select v-model="currentRow.languageId" placeholder="请选择">
                      <el-option
                        v-for="item in langOptions"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value">
                      </el-option>
                    </el-select>
                </el-form-item>
              <el-form-item label="内容名称" :label-width="formLabelWidth">
                <el-input v-model="currentRow.name"></el-input>
              </el-form-item>
                 <el-form-item label="内容标题" :label-width="formLabelWidth">
                    <el-input v-model="currentRow.title"></el-input>
                </el-form-item>
              <el-form-item label="内容简介" :label-width="formLabelWidth">
                <el-input v-model="currentRow.introduce"></el-input>
              </el-form-item>
              <el-form-item label="Logo" :label-width="formLabelWidth">
                <el-upload
                  class="logo-uploader"
                  :action="url"
                  :data="filesData"
                  name="files"
                  :show-file-list="false"
                  :on-success="upfateLogoSuccess"
                  :on-error = "handleLogoFailed"
                  :before-upload="beforeLogoUpload"
                  :headers="headers">
                  <img v-if="updateSrc" :src="updateSrc" class="logo">
                  <i v-else class="el-icon-plus logo-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="外链" :label-width="formLabelWidth">
                <el-input v-model="currentRow.outChain"></el-input>
              </el-form-item>
                <el-form-item label="内容内容" :label-width="formLabelWidth">
                   <rich-text-editor ref='editor1' :Id='2' ></rich-text-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click='closeEditDialog'>取 消</el-button>
                <el-button type="primary" @click="editContent" :loading="btnLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {returnFilesUrl,returnThumbnailUrl,uploadFile,uploadUrl} from '@/modules/file/api/upload'
import pagination from '@/components/pagination/index'
import {selectLanguage} from '../api/language'
import richTextEditor from '@/components/richTextEditor/index'
import {getContentList, updateContent, addContent, deleteContentes} from '../api/article_content'
export default {
    name:'articleList',
    data(){
        return {
            module:"article",
            tableData:[],
            btnLoading:false,
            addArticleDialog:false,
            multipleSelection: [], // 选中数据-多选
            totalElements:0,
            loading:false,
            formLabelWidth:'80px',
            url: uploadUrl + "/article" ,
            langOptions:[],
            editDialog:false,
            specListForm:{
            list:[],
            },
           imgSrc: '',
           updateSrc: '',
            form:{
              languageId:'',
              name:'',
              introduce:'',
              articleId:'',
              outChain:'',
              title: '',
              photo: '',
              details: ''
            },
          currentRow: {
            id: '',
            name: '',
            languageId: '',
            title: '',
            photo: '',
            introduce: '',
            details: '',
            outChain: '',
          },
           imgSrc: '',
            current:{
                langType:'',
                name:'',
              value:'',
            },
          filesData: {
            module: 'article'
          },
          headers: {
            authorized: sessionStorage.token
          } // 请求头部
        }
    },
    components: { pagination, richTextEditor},
  created(){
      console.log(this.$route.query.id);
    this.getContentList();
  },
    methods:{
      handleSelectionChange (val) {
        this.multipleSelection = val
      },
      handleDelete (row) {
        this.multipleSelection.push(row)
        this.deleteContentes()
      },
        /**
         * 获取一级内容列表
         * */
        getContentList: function (number, pageSize) {
          this.loading = true
          getContentList(number, pageSize,this.$route.query.id).then(response => {
            this.tableData = response.obj.content
            this.totalElements = response.obj.totalElements
            for (let i = 0; i < this.tableData.length; i++) {
              this.tableData[i].fileSrc = this.tableData[i].photo
              this.tableData[i].photo = returnThumbnailUrl(this.tableData[i].photo)
            }
            console.log(this.tableData)
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        },
        /**
         * 打开添加内容对话框
         * */
        openAddDialog(){
            this.addArticleDialog = true;
          this.selectLanguage()
            setTimeout(()=>{
                this.$refs.editor2.init();
            },20)
        },
      /*
      * 打开内容模态框
      * */
        addContent () {
        this.loading = true
        this.btnLoading = true;
        this.$refs.editor2.getContent();
        this.form.details = this.$refs.editor2.content;
        this.form.articleId = this.$route.query.id;
        console.log('列表', this.form)
          addContent(this.form).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.btnLoading = false
            this.loading = false;
            this.initEditor2();
          this.closeCreatedDialog();
            this.getContentList();
        }).catch(() => {
          this.btnLoading = false
          this.loading = false
            this.initEditor2();
        })
      },
      // 获取所有口味
      selectLanguage() {
        if (!this.langOptions.length) {
          selectLanguage().then(response => {
            this.langOptions = response.obj
          }).catch(() => {})
        }
      },
         /**
         * 关闭添加内容对话框
         * */
        closeAddDialog(){
            this.addArticleDialog = false;
            this.form = {
              languageId:'',
              name:'',
              introduce:'',
              articleId:'',
              outChain:'',
              title: '',
              photo: '',
              details: ''
            }
            this.initEditor2();

        },
        /**
         * 打开编辑内容对话框
         * */
        openEditDialog(row){
          this.editDialog = true;
          this.selectLanguage()
          this.currentRow.id = row.id
          this.currentRow.name = row.name
          this.currentRow.languageId = row.languageId
          this.currentRow.title = row.title
          this.currentRow.introduce = row.introduce
          this.currentRow.fileSrc = row.fileSrc
          this.updateSrc = row.photo
          this.currentRow.outChain = row.outChain
            setTimeout(()=>{
              this.$refs.editor1.init();
            },20)
            setTimeout(()=>{
              this.$refs.editor1.setContent(row.details);
            },100)
        },
      /*
   * 编辑
   * */
      editContent () {
        this.loading = true
        this.btnLoading = true;
        this.$refs.editor1.getContent();
        this.currentRow.details = this.$refs.editor1.content;
        updateContent(this.currentRow).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.btnLoading = false
          this.loading = false;
          this.closeEditDialog()
          this.refresh()
        }).catch(() => {
          this.loading = false
          this.btnLoading = false
        })
      },
      /*
        * 删除食品
        * */
      deleteContentes () {
        this.$confirm('是否删除内容内容？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.multipleSelection.length) {
            this.loading = true
            let ids = []
            this.multipleSelection.forEach((item) => {
              ids.push(item.id)
            })
            deleteContentes(ids).then(response => {
              this.$message({
                message: response.msg,
                type: 'success',
                duration: 1000
              })
              this.multipleSelection = []
              this.$refs.page.refresh()
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.$message({
              message: '请选择内容',
              type: 'warning',
              duration: 1000
            })
          }
        })
      },

        initEditor1(){
          this.$refs.editor1.setContent('');
          this.$refs.editor1.destory();
        },
        initEditor2(){
          this.$refs.editor2.setContent('');
          this.$refs.editor2.destory();
        },
        /**
         * 关闭编辑内容对话框
         * */
        closeEditDialog(){
            this.editDialog = false;
            this.currentRow = {
              id: '',
              name: '',
              languageId: '',
              title: '',
              photo: '',
              introduce: '',
              details: '',
              outChain: '',
            };
            this.initEditor1();
        },
      /*
    * logo上传成功
    * */
      handleLogoSuccess (response, file) {
        this.$message({
          message: response.msg,
          type: 'success'
        })
        this.form.photo = response.obj
        this.imgSrc = returnFilesUrl(response.obj)
      },
      upfateLogoSuccess (response, file) {
        this.$message({
          message: response.msg,
          type: 'success'
        })
        this.currentRow.fileSrc = response.obj
        this.updateSrc = returnFilesUrl(response.obj)
      },
      /*
    * logo上传失败
    * */
      handleLogoFailed () {
        this.$message({
          message: '图片上传失败',
          type: 'error'
        })
      },
      /*
   * 对logo类型、大小做限制
   * */
      beforeLogoUpload (file) {
        let isImage = file.type.substring(0, 5) === 'image'
        if (!isImage) {
          this.$message.error('只能上传图片')
          return false
        }
        return true
      },
      /*
 * 关闭门店模态框
 * */
      closeCreatedDialog () {
        this.addArticleDialog = false
        this.form = {
          title: '',
          introduce: '',
          details: '',
          photo: '',
          outChain: '',
          languageId: '',
        } // 门店数据
        this.imgSrc = ''
      },
        /**
         * 刷新
         * */
        refresh(){
            this.$refs.page.refresh();
        },
        onReady(){
            console.log(123);
        }
    }
}
</script>


<style scoped>
  .logo-uploader {
    display: inline-block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .logo-uploader:hover {
    border-color: #409EFF;
  }
  .logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .logo {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
